<template>
  <div>
    <vxe-toolbar id="toolbarId" :setting="{storage: true}" export :refresh="{query: findList}">
      <template v-slot:buttons>
        <el-button @click="funcFilter">查询</el-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      highlight-hover-row
      height="700"
      :data="tableData"
      :loading="loading"
      remote-sort
      @sort-change="sortList"
    >
      <vxe-table-column type="checkbox" width="60" />
      <vxe-table-column>
        <vxe-table-column
          field="netStatus"
          title="定位状态"
          :formatter="formatterNetStatus"
          min-width="130"
          sortable
        />
        <template v-slot:header>
          <el-select v-model="listQuery.netStatus" placeholder="请选择" clearable>
            <el-option
              v-for="item in netStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="owner" title="车主姓名" min-width="130" sortable />
        <template v-slot:header>
          <el-input v-model="listQuery.owner" placeholder="请输入车主姓名" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="licenseNumber" title="车牌号" min-width="130" sortable />
        <template v-slot:header>
          <el-input v-model="listQuery.licenseNumber" placeholder="请输入车牌号" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="classificationCode"
          title="车辆分类"
          :formatter="formatterVehicleClassification"
          min-width="130"
          sortable
        />
        <template v-slot:header>
          <el-select v-model="listQuery.classificationCode" placeholder="请选择" clearable>
            <el-option
              v-for="item in vehicleClassificationList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
              clearable
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="loadWeight"
          title="车辆可载重量"
          :formatter="formatterLoadWeight"
          min-width="130"
          sortable
        />
        <template v-slot:header>
          <el-select v-model="listQuery.loadWeight" placeholder="请选择" clearable>
            <el-option
              v-for="item in vehicleTonnageList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
              clearable
            />
          </el-select>
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column
          field="authStatus"
          title="审核状态"
          :formatter="formatterAuthStatus"
          min-width="130"
          sortable
        />
        <template v-slot:header>
          <el-select v-model="listQuery.authStatus" placeholder="请选择" clearable>
            <el-option
              v-for="item in authStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="loadStatus"
          title="载重状态"
          :formatter="formatterLoadStatus"
          min-width="130"
          sortable
        />
        <template v-slot:header>
          <el-select v-model="listQuery.loadStatus" placeholder="请选择" clearable>
            <el-option
              v-for="item in loadStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="isFreeze"
          title="是否冻结"
          :formatter="formatterIsFreeze"
          min-width="130"
          sortable
        />
        <template v-slot:header>
          <el-select v-model="listQuery.isFreeze" placeholder="请选择" clearable>
            <el-option
              v-for="item in isFreezeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="locationSource"
          title="定位来源"
          :formatter="formatterLocationSource"
          min-width="130"
          sortable
        />
        <template v-slot:header>
          <el-select v-model="listQuery.locationSource" placeholder="请选择" clearable>
            <el-option
              v-for="item in locationSourceList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
              clearable
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtCreated"
          title="创建时间"
          min-width="420"
          :resizable="false"
          sortable
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtCreatedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtCreated')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column title="操作" fixed="right" min-width="150">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="详情" placement="top">
            <vxe-button type="text" @click="funcDetail(scope.row.code)">
              <i class="el-icon-document" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="车辆定位" placement="top">
            <vxe-button type="text" @click="funcVehicleTrail(scope.row.code)">
              <i class="el-icon-location-information" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip
            v-if="scope.row.isFreeze == 0"
            class="item"
            effect="dark"
            content="冻结"
            placement="top"
          >
            <vxe-button type="text" @click="lockCar(scope.row.code)">
              <i class="el-icon-lock" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip
            v-if="scope.row.isFreeze == 1"
            class="item"
            effect="dark"
            content="解除冻结"
            placement="top"
          >
            <vxe-button type="text" @click="unlockCar(scope.row.code)">
              <i class="el-icon-unlock" />
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
      @page-change="handlePageChange"
    />

    <vxe-modal v-model="modelDetailFlag" title="详情" width="800" height="600" resize>
      <compDetail
        ref="detailRef"
        :parent-data="{
        vehicleClassificationList,
        vehicleLengthList,
        vehicleWidthList,
        vehicleHighList,
        vehicleTonnageList,
        locationSourceList}"
      />
    </vxe-modal>
    <vxe-modal v-model="modelVehicleTrailFlag" title="车辆定位" width="900" height="700" resize>
      <compVehicleTrail ref="vehicleTrailRef" />
    </vxe-modal>
  </div>
</template>
<script>
import Vue from "vue";
import "xe-utils";
import VXETable from "vxe-table";
import "vxe-table/lib/index.css";
import XEUtils from "xe-utils";
import VXEUtils from "vxe-utils";
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ["cookie"] });
import compDetail from "./components/vehicleDetail.vue";
import compVehicleTrail from "./components/vehicleTrail.vue";
import { vehicle } from "@/api/transport";
import { freezeVehicle, unfreezeVehicle } from "@/api/driver";
import { getListDict } from "@/api/commonApi";
export default {
  name: "PlatVehicle",
  components: {
    compDetail,
    compVehicleTrail
  },
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      loading: false,
      tableData: [],
      modelDetailFlag: false,
      modelVehicleTrailFlag: false,
      listQuery: {
        code: "",
        licenseNumber: "",
        branchCode: "",
        teamCode: "",
        licensePlateType: "",
        classificationCode: "",
        roadTransportCertificateNumber: "",
        roadTransportCertificateImg: "",
        roadTransportCertificateDate: "",
        loadWeight: "",
        loadVolume: "",
        remainingLoadWeight: "",
        remainingLoadVolume: "",
        vehicleLicenseColor: "",
        vehicleLicenseImg: "",
        vehicleLicenseDueDate: "",
        vehicleImg: "",
        isHasTrailer: "",
        trailerNum: "",
        trailerVehicleLicenseImg: "",
        trailerRoadTransport: "",
        trailerRoadTransportCertificateImg: "",
        trailerVehicleImg: "",
        authStatus: "",
        loadStatus: "",
        isFreeze: "",
        locationSource: "",
        netStatus: "",
        terminalNumber: "",
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      gmtCreatedRange: "",
      vehicleClassificationList: [],
      vehicleLengthList: [],
      vehicleWidthList: [],
      vehicleHighList: [],
      vehicleTonnageList: [],
      locationSourceList: [],
      // 定位状态
      netStatusOptions: [
        { label: "未定位", value: 0 },
        { label: "定位成功", value: 1 }
      ],
      // 载重状态
      loadStatusOptions: [
        { label: "空载", value: 0 },
        { label: "负载", value: 1 }
      ],
      // 审核状态
      authStatusOptions: [
        { label: "未审核", value: 0 },
        { label: "审核中", value: 1 },
        { label: "审核未通过", value: 2 },
        { label: "审核通过", value: 3 }
      ],
      // 是否冻结
      isFreezeOptions: [
        { label: "未冻结", value: 0 },
        { label: "已冻结", value: 1 }
      ]
    };
  },
  created() {
    // 获取数据字典： 车型，车长，车宽，车高，吨位，定位来源
    getListDict({
      types:
        "vehicleClassification,vehicleLength,vehicleWidth,vehicleHigh,vehicleTonnage,locationSource"
    }).then(response => {
      this.vehicleClassificationList = response.data.filter(
        item => item.type === "vehicleClassification"
      )[0]["dictList"];
      this.vehicleLengthList = response.data.filter(
        item => item.type === "vehicleLength"
      )[0]["dictList"];
      this.vehicleWidthList = response.data.filter(
        item => item.type === "vehicleWidth"
      )[0]["dictList"];
      this.vehicleHighList = response.data.filter(
        item => item.type === "vehicleHigh"
      )[0]["dictList"];
      this.vehicleTonnageList = response.data.filter(
        item => item.type === "vehicleTonnage"
      )[0]["dictList"];
      this.locationSourceList = response.data.filter(
        item => item.type === "locationSource"
      )[0]["dictList"];
      this.findList();
    });
  },
  methods: {
    findList() {
      this.loading = true;
      return new Promise(resolve => {
        vehicle(this.listQuery).then(response => {
          this.tableData = response.data.records;
          this.listQuery.total = response.data.total;
          this.loading = false;
          resolve();
        });
      });
    },
    // 批量上传
    funcBatchUp() {
      this.checkedRowArray = this.$refs.xTable.getSelectRecords();
      if (!this.checkedRowArray || this.checkedRowArray.length === 0) {
        this.$message({ message: "请选择要上传的车辆", type: "warning" });
      } else {
        this.$message({ message: "上传成功", type: "success" });
        // const checkCodeArray = []
        // this.checkedRowArray.forEach(item => {
        //   checkCodeArray.push(item.partyCode)
        // })
        // const checkPartyCodes = checkCodeArray.join(',')
        // request({ url: '/ntocc-tms-api/', method: 'post', params: { teamCodes: checkPartyCodes }}).then(response => {
        //   this.$message({ message: '上传成功', type: 'success' })
        //   this.findList()
        // })
      }
    },
    // 详情方法
    funcDetail(code) {
      this.$refs.detailRef.getInfo(code);
      this.modelDetailFlag = true;
    },
    // 车辆历史跟踪方法
    funcVehicleTrail(code) {
      this.$refs.vehicleTrailRef.trajectory(code);
      this.modelVehicleTrailFlag = true;
    },
    // 查询
    funcFilter() {
      this.listQuery.pageNum = 1;
      this.findList();
    },
    // 排序
    sortList({ column, property, order }) {
      if (order) {
        this.listQuery.sortField = property;
        this.listQuery.sortType = order;
      } else {
        this.listQuery.sortField = "";
      }
      this.findList();
    },
    // 冻结
    lockCar(code) {
      this.$confirm("确认冻结吗？")
        .then(_ => {
          freezeVehicle({ code }).then(response => {
            this.$message({ message: response.msg, type: "success" });
            this.findList();
          });
        })
        .catch(_ => {});
    },
    // 解除冻结
    unlockCar(code) {
      this.$confirm("确认解除冻结吗？")
        .then(_ => {
          unfreezeVehicle({ code }).then(response => {
            this.$message({ message: response.msg, type: "success" });
            this.findList();
          });
        })
        .catch(_ => {});
    },
    // 时间
    changeDate(value, prefix) {
      if (value) {
        this.listQuery[`${prefix}Start`] = value[0] + " 00:00:00";
        this.listQuery[`${prefix}End`] = value[1] + " 23:59:59";
      } else {
        this.listQuery[`${prefix}Start`] = "";
        this.listQuery[`${prefix}End`] = "";
      }
    },
    // 翻译审核状态
    formatterAuthStatus({ cellValue }) {
      const item = this.authStatusOptions.find(
        item => item.value === cellValue
      );
      return item ? item.label : "";
    },
    // 翻译定位状态
    formatterNetStatus({ cellValue }) {
      const item = this.netStatusOptions.find(item => item.value === cellValue);
      return item ? item.label : "";
    },
    // 翻译车型
    formatterVehicleClassification({ cellValue }) {
      const item = this.vehicleClassificationList.find(
        item => item.code === cellValue
      );
      return item ? item.name : "";
    },
    // 翻译可载重量
    formatterLoadWeight({ cellValue }) {
      const item = this.vehicleTonnageList.find(
        item => item.code === cellValue
      );
      return item ? item.name : "";
    },
    // 翻译载重状态
    formatterLoadStatus({ cellValue }) {
      const item = this.loadStatusOptions.find(
        item => item.value === cellValue
      );
      return item ? item.label : "";
    },
    // 翻译是否冻结
    formatterIsFreeze({ cellValue }) {
      const item = this.isFreezeOptions.find(item => item.value === cellValue);
      return item ? item.label : "";
    },
    // 翻译定位来源
    formatterLocationSource({ cellValue }) {
      const item = this.locationSourceList.find(item => item.code == cellValue);
      return item ? item.name : "";
    },
    // 公共取消
    fatherCancel(modelFlag) {
      switch (modelFlag) {
        case "add":
          this.modelAddFlag = false;
          break;
        case "edit":
          this.modelEditFlag = false;
          break;
        case "detail":
          this.modelDetailFlag = false;
          break;
        default:
      }
    },
    // 分页handle
    handlePageChange({ currentPage, pageSize }) {
      this.listQuery.pageNum = currentPage;
      this.listQuery.pageSize = pageSize;
      this.findList();
    }
  }
};
</script>
